<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\WaterStorage;
use App\Models\WaterMyStorage;
use DB;

class WaterStorageController extends Controller
{
    protected $message = [
        'name.required' => '商品名称必须',
        'name.max' => '商品名称不能超过100个字符',
              
        'company_id.required' => '项目必须',
        'company_id.integer' => '项目格式为整数值',
        'company_id.exists' => '项目不存在',
        
        'site_id.required' => '站点必须',
        'site_id.integer' => '站点格式为整数值',
        'site_id.exists' => '站点不存在',
        
        'shops.array'=>"商品参数错误",
        'shops.min'=>"至少选择一个商品",
        
        'shops.*.num.required' => '数量必须',
        'shops.*.num.integer' => '数量格式为整数值',
        'shops.*.price.required' => '单价必须',
        'shops.*.price.integer' => '单价格式为数值',
    ];
    /**
     * 入库单列表
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $perPage = $request->input('pageSize',15);
        $name = $request->input('name', '');
        $query = WaterStorage::query();
        if(!empty($name)) {
            $query->where('name', 'like', $name.'%');
        }
        $cid = $request->input('company', '');
        if(!empty($cid)) {
            $query->where('company_id', $cid);
        }
        $sid = $request->input('site', '');
        if(!empty($sid)) {
            $query->where('site_id', $sid);
        }
        
        $status = $request->input('status', '');
        if(trim($status)!=="") {
            $query->where('status', $status);
        }
        
        $created = $request->input('created_at', []);
        if(!empty($created)) {
            $query->whereBetween('created_at', $created);
        }
        
        $query->with([
            'companies' => function($query) {
                $query->select(['Co_ID', 'Co_Name']);
            },
            'sites' => function($query) {
                $query->select(['id', 'name']);
            },
            'shops'=> function($query) {
                $query->select(['id', 'name', "unit"]);
            },
        ]);
        $list = $query->paginate($perPage);
        return $list;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * 添加入库单.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // $data = $request->input();

        $data = $this->validateData($request);
        $user = $request->user();
        $data['creater_uid'] = $user->userid;
        $data['creater_name']= $user->username;
        // $data['company_id'] = $user->Co_ID;
       // $data['site_id']= $user->scope;
       $shops = $data['shops'];
       unset($data['shops']);
       $ret = WaterStorage::create($data);
       
       
       $attachData = collect($shops)->map(function($item){
           return collect($item)->only(['num', 'price', 'id']);
       })
        ->keyBy('id')
        ->map(function($item){
           return collect($item)->except(['id'])->all();
       });
       
       $ret->shops()->attach($attachData->all()); 
       // $ret->shops()->save();
        if(!$ret){
            $this->error('保存失败');
        }
    }
    
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 更新入库单.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // $data = $request->input();

        $data = $this->validateData($request, $id);
        
        $ws = WaterStorage::find($id);
        
        $shops = $data['shops'];
        
        $pivotData = collect($shops)->map(function($item){
           return collect($item)->only(['num', 'price', 'id']);
       })
        ->keyBy('id')
        ->map(function($item){
           return collect($item)->except(['id'])->all();
       });
        $ret = $ws->update($data);
        if($ret) {
            $ws->shops()->sync($pivotData->all());
        }
        if(!$ret){
            $this->error('保存失败');
        }
    }
    
    //验证表单
    protected function validateData($request,$id = false) {

        $rules = [
            'shops' => ["array", "min:1"],
            'shops.*.num' => 'required|integer',
            'shops.*.price' => 'required|numeric',
        ];


        $v = $this->validate2($request, $rules, $this->message);
        
        $user = $request->user();
        $isSuper = $user->isSuper();
        $isSuperAdmin = $user->isSuperAdmin();
        
        $v->sometimes('company_id', 'required|integer|exists:t_companycnfo,Co_ID', function()use($isSuper) {
            return $isSuper;
        });
        
        $v->sometimes('site_id', 'required|integer|exists:sites,id', function()use($isSuperAdmin) {
            return $isSuperAdmin;
        });
        $data = $request->input();
        if(!$isSuper) {
            $data['company_id'] = $user->Co_ID;
        }
        if(!$isSuperAdmin) {
            $data['site_id'] = $user->scope;
        }
        
       $v->validate();
       return $data;
    }

    /**
     * 删除入库单
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $ws = WaterStorage::findOrFail($id);
        if(!$ws->delete()){
            $this->error('删除失败');
        }
    }
    
    /**
     * 更新商品库存
     */
    public function updateShopStorage(Request $request, $id) {
        $ws = WaterStorage::find($id);
        if($ws->status!=0) {
            $this->error('入库单状态不正确');
        }
        $user = $request->user();
        $shops = $ws->shops();
        try {
            DB::transaction(function () use($shops, $ws, $user){
                $inputs = [
                    'company_id'=>$ws->company_id,
                    'site_id'=>$ws->site_id,
                ];
                $this->updateMyStorage($inputs, $shops);
                //更新入库单状态
                $data = ['status'=>1, 'confirm_uid'=>$user->userid, 'confirm_name'=>$user->username];
                $ws->update($data);
                addActivityLog(':causer.username 确认入库单【:subject.id】入库 ', $ws ,'storage', $data);
            }); 
            return "入库成功";
        } catch (Exception $ex) {
            $this->error('入库失败');
        }
        
    }
    
    //更新库存
    protected function updateMyStorage($inputs, $data) {
        $data->each(function($item) use($inputs){
            $itemData = [
                'shop_id'=>$item->id,
                'company_id'=> array_get($inputs, 'company_id'),
                'site_id'=> array_get($inputs, 'site_id')
            ];
            $num = data_get($item, 'pivot.num', 0);
            $find = WaterMyStorage::firstOrCreate($itemData);
            $find->increment('num', $num);
        });
    }
}
